package com.puppy.uhfreader;

import UHF18.UHFReader;
import cn.hutool.core.date.DateTime;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

//import java.awt.*;
import java.awt.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDate;
import java.util.*;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import utils.FileUtil;
import utils.GetCameraPreviewURL;

/*
 * @Author: puppy
 * @CreateDate: 2023-06-17 17:09:00
 * @FullNameClass: $path$
 * @Description:
 * @path com.puppy.uhfreader.mainNoFrame
 */
public class MainNoFrame {


//    private static String ipaddr="192.168.75.202";
//    private static final int Port = 6000;
    private static UHFReader uhf = new UHFReader();
    private static String[] EPC;
    private static String sepc;
    private static String location;//车当前位置变量
    private static  final String[] local = {"P1","P2","P3","P4","P5","P6","P7","P8","P9","P10"};//车工位汇总
    private static String res = "";
    private static Properties properties = new Properties();
//    private static ArrayList<Account> data = new ArrayList<>();
//    private static String temp[][] = {{"1","1","1"},{"1","1","1"}};
    private static String filePath = "src/main/resources/" ;

    static Runnable rfidRun = new Runnable() {//-server -XX:PermSize=128M -XX:MaxPermSize=256m
        @Override
        public void run() {

            EPC=uhf.Inventory();
            if(EPC != null ){
                for(int m=0;m<EPC.length;m++  ) {
                    /**
                     * sepc:判断为空or（不为空并且与RFID接收数据不一致）
                     * 为空：代表第一次
                     * 不为空并且与RFID接收数据不一致：则需要重新加载摄像，如果一致则不切换摄像头。
                     */
                    if (sepc == null || (sepc != null && (!sepc.equals(EPC[m])))){
                        //读取配置文件中是否有配置的卡号，有则继续下一步，无则不调用HIK接口
                        sepc = EPC[m];
                        System.out.println(DateTime.now() + ">>>>>>>>>>" + "current cardNo:".concat(sepc));
                        for (int i = 0; i < local.length; i ++){
                            Object ObjectPCards = properties.get(local[i]);
                            if(ObjectPCards != null && !ObjectPCards.equals("")){
                                String[] arrayPCards = ObjectPCards.toString().split("&");
                                if(Arrays.stream(arrayPCards).anyMatch(s -> s.equals(sepc))){//判断是否在这个打卡位置
                                    if(local[i].equals(location)){
                                        System.out.println( DateTime.now() +  ">>>>>>>>>>" + "judge one same location's diff card:".concat(sepc));
                                        break;
                                    }else {//当前卡号所在组与上次查询到的组不同，代表更新了工位
                                        System.out.println(DateTime.now() +  ">>>>>>>>>>" + sepc);
                                        location = local[i];
                                        Map<String,Object> params = new HashMap<>();
                                        params.put("epcNo" ,sepc);
                                        params.put("appkey" ,properties.getProperty("Appkey"));
                                        params.put("appsecret" ,properties.getProperty("secret"));
//                                    res = HttpUtil.post("https://192.168.81.145:443/artemis/api/vics/v1/sendRFID",params);
                                        // TODO 判断，卡号是不是在配置 项里
                                        res = GetCameraPreviewURL.GetCameraPreviewURL(sepc);

                                        FileUtil.writeFile(filePath, LocalDate.now().toString().concat(".txt"), sepc.concat(":").concat(res == null ?"":res));
                                    }
                                }
                            }
                        }


/*





/*                        if(index > 0){
                            try{
                                sepc = EPC[m];
                                System.out.println(sepc);
//                                        data.clear();
                            }catch (Exception ex){
                                continue;
                            }
                            //TODO 在此处调用接口
                            Map<String,Object> params = new HashMap<>();
                            params.put("epcNo" ,sepc);
                            params.put("appkey" ,properties.getProperty("Appkey"));
                            params.put("appsecret" ,properties.getProperty("secret"));
//                                    res = HttpUtil.post("https://192.168.81.145:443/artemis/api/vics/v1/sendRFID",params);
                            // TODO 判断，卡号是不是在配置 项里
                            res = GetCameraPreviewURL.GetCameraPreviewURL(sepc);

                            FileUtil.writeFile(filePath, LocalDate.now().toString().concat(".txt"), sepc.concat(":").concat(res == null ?"":res));

                        *//*try{
                            Object o = properties.get(sepc);
                            if(o != null){
                                String accouts = properties.get(sepc).toString();
                                String[] element = accouts.split("&");
                                System.out.println(">>>>>>>>>>" + accouts);
                                temp[0][0] = element[0].toString();
                                temp[0][1] = element[1].toString();
                                temp[0][2] = element[2].toString();
                                temp[1][0] = element[3].toString();
                                temp[1][1] = element[4].toString();
                                temp[1][2] = element[5].toString();

                            }

//                                        TwoCamerasWindow.run(temp);
//                                        args= null;
                        }catch (Exception ex){
                            ex.printStackTrace();
                            System.out.println("卡号不对！！！！！！！！！\n卡号不对！！！！！！！！！\n卡号不对！！！！！！！！！\n卡号不对！！！！！！！！！\n卡号不对！！！！！！！！！\n卡号不对！！！！！！！！！\n卡号不对！！！！！！！！！\n");
                        }*//*
                        }*/
                    }
                }
            }
        }
    };
    public static void main(String[] args) throws InterruptedException {

        System.out.println("************invokeAndWait************");
        try {
            properties.load(new FileInputStream("src/main/resources/config.properties"));
            uhf.OpenByTcp(properties.getProperty("ipaddr"), Integer.parseInt(properties.getProperty("port")));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(500);
        Runnable task = () -> {

            // 你的任务逻辑
            // 确保这里经常检查 Thread.currentThread().isInterrupted()，以便能够响应中断
            if(Thread.currentThread().isInterrupted()){
//                System.gc();
                FileUtil.writeFile(filePath, LocalDate.now().toString().concat(".txt"), "Thread.currentThread().isInterrupted()");
            }
            try {
                EventQueue.invokeAndWait(rfidRun);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
//            EventQueue.invokeLater(rfidRun);
        };
        executorService.scheduleAtFixedRate(task, 0, 500, TimeUnit.MILLISECONDS);
    }
}

